/**
 * 
 */
package com.cp16.tss.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;

import com.cp16.tss.dto.Customer;

/**
 * @author ADMIN
 * 
 */
public class CustomerDAO {
	
	SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
	
	public Customer getCustomerById(int customerId) throws Exception {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Customer cus = (Customer) session.get(Customer.class, customerId);
		session.getTransaction().commit();
		session.close();
		return cus;
	}

	public List<Customer> getCustomerByName(String customerName) throws Exception {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		//Customer cus = (Customer) session.get(Customer.class, customerName);
		@SuppressWarnings("unchecked")
		List<Customer> customerList = session.createCriteria(Customer.class).add(
				Restrictions.like("customerName", customerName)).list();
		session.getTransaction().commit();
		session.close();
		return customerList;
	}
	
	public List<Customer> getAllCustomer(){
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(Customer.class);
		@SuppressWarnings("unchecked")
		List<Customer> customerList = criteria.list();
		session.getTransaction().commit();
		session.close();
		return customerList;
	}

	public boolean addCustomer(Customer customer) throws Exception {
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			session.save(customer);
			session.getTransaction().commit();
			session.close();
			return true;
	}

	public boolean updateCustomer(Customer customer) throws Exception {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		try {
			session.update(customer);
			session.getTransaction().commit();
			return true;
		} catch (HibernateException e) {
			session.getTransaction().rollback();
			e.printStackTrace();
			return false;
		} finally {
			session.clear();
			session.close();
		}
	}

	public boolean deleteCustomer(Customer customer) throws Exception{
		try {
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			session.delete(customer);
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean checkCustomerExist(int customerId) throws Exception{
		Customer cus = getCustomerById(customerId);
		if (cus != null) {
			return true;
		} else {
			return false;
		}
	}
	
}
